package com.activemq.maintance;

import com.activemq.MqHelloWorld;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.springframework.boot.autoconfigure.jms.JmsProperties;

import javax.jms.*;

/**
 * 非持久订阅，只有先启动了消费者，然后再启动生产者，消费者不挂，才会接收到消息，消费者挂了消息就丢了（容忍丢失）
 * 持久订阅：客户端向MQ注册ClientId，当客户端离线，消息不会丢失，等到消费者启动的时候会接收到消息（持久订阅）
 */
@Slf4j
public class MsgSubscribe {
    public static final String TOPIC_NAME = "SUBSCRIBE_TOPIC";

    public static void main(String[] args) throws Exception {
        /*
          先运行一次消费者，等于向MQ注册
          然后运行生产者发送消息
          然后就可以收到消息，在线即刻收到，离线会把历史消息都接收下来
         */
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.setClientID("z3");
        Session session = connection.createSession(false, JmsProperties.AcknowledgeMode.AUTO.getMode());
        Topic topic = session.createTopic(TOPIC_NAME);
        TopicSubscriber durableSubscriber = session.createDurableSubscriber(topic, "remarks..");
        //持久化消息拉取
        durableSubscriber.setMessageListener((message) -> {
            try {
                if (message instanceof TextMessage) {
                    log.error(((TextMessage) message).getText());
                }
            } catch (JMSException e) {
                log.error("出错", e);
            }
        });
        connection.start();
        System.in.read();
        durableSubscriber.close();
        session.close();
        connection.close();
    }
}

@Slf4j
class MsgSubscribeZ4 {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.setClientID("z4");
        Session session = connection.createSession(false, JmsProperties.AcknowledgeMode.AUTO.getMode());
        Topic topic = session.createTopic(MsgSubscribe.TOPIC_NAME);
        TopicSubscriber durableSubscriber = session.createDurableSubscriber(topic, "remarks..");
        //持久化消息拉取
        durableSubscriber.setMessageListener((message) -> {
            try {
                if (message instanceof TextMessage) {
                    log.error(((TextMessage) message).getText());
                }
            } catch (JMSException e) {
                log.error("出错", e);
            }
        });
        connection.start();
        System.in.read();
        durableSubscriber.close();
        session.close();
        connection.close();
    }
}